<!doctype html>



  


<html class="theme-next mist use-motion">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>



<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />












  <link href="/vendors/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css"/>




  <link href="//fonts.useso.com/css?family=Lato:300,400,700,400italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">



<link href="/vendors/font-awesome/css/font-awesome.min.css?v=4.4.0" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=0.5.0" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="java," />





  <link rel="alternate" href="/atom.xml" title="Lippi-浮生志" type="application/atom+xml" />




  <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=0.5.0" />






<meta name="description" content="许多热门的编程语言如今都有一个叫做lambda或者闭包的语言特性，包括比较经典的函数式编程语言Lisp,Scheme,也有稍微年轻的语言比如JavaScript,Python,Ruby,Groovy,Scale,C#,甚至C++也有Lambda表达式。一些语言是运行在java虚拟机上，作为虚拟机最具代表的语言java当然也不想落后。">
<meta property="og:type" content="article">
<meta property="og:title" content="Java Lambda简明教程">
<meta property="og:url" content="http://www.ezlippi.com/blog/2015/06/java-lambda-expression.html">
<meta property="og:site_name" content="Lippi-浮生志">
<meta property="og:description" content="许多热门的编程语言如今都有一个叫做lambda或者闭包的语言特性，包括比较经典的函数式编程语言Lisp,Scheme,也有稍微年轻的语言比如JavaScript,Python,Ruby,Groovy,Scale,C#,甚至C++也有Lambda表达式。一些语言是运行在java虚拟机上，作为虚拟机最具代表的语言java当然也不想落后。">
<meta property="og:updated_time" content="2016-02-29T13:03:46.000Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Java Lambda简明教程">
<meta name="twitter:description" content="许多热门的编程语言如今都有一个叫做lambda或者闭包的语言特性，包括比较经典的函数式编程语言Lisp,Scheme,也有稍微年轻的语言比如JavaScript,Python,Ruby,Groovy,Scale,C#,甚至C++也有Lambda表达式。一些语言是运行在java虚拟机上，作为虚拟机最具代表的语言java当然也不想落后。">



<script type="text/javascript" id="hexo.configuration">
  var NexT = window.NexT || {};
  var CONFIG = {
    scheme: 'Mist',
    sidebar: {"position":"left","display":"post"},
    fancybox: true,
    motion: true,
    duoshuo: {
      userId: 0,
      author: '博主'
    }
  };
</script>

  <title> Java Lambda简明教程 | Lippi-浮生志 </title>
</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  



  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "//hm.baidu.com/hm.js?340874ba9357cbe81570aa4ac1185941";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>






  
  
    
  

  <div class="container one-collumn sidebar-position-left page-post-detail ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner">
<script>
(function(){
    var bp = document.createElement('script');
    bp.src = '//push.zhanzhang.baidu.com/push.js';
    var s = document.getElementsByTagName("script")[0];
    s.parentNode.insertBefore(bp, s);
})();
</script>
            
<div class="site-meta ">
  

  <div class="custom-logo-site-title">
    <a href="/"  class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <span class="site-title">Lippi-浮生志</span>
      <span class="logo-line-after"><i></i></span>
    </a>
  </div>
  <p class="site-subtitle"></p>
</div>

<div class="site-nav-toggle">
  <button>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
  </button>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu menu-left">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-home fa-fw"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories" rel="section">
            
              <i class="menu-item-icon fa fa-th fa-fw"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives" rel="section">
            
              <i class="menu-item-icon fa fa-archive fa-fw"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags" rel="section">
            
              <i class="menu-item-icon fa fa-tags fa-fw"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about" rel="section">
            
              <i class="menu-item-icon fa fa-user fa-fw"></i> <br />
            
            关于
          </a>
        </li>
      

      
      
      
    </ul>
  

  
    <div class="site-search">
      
  <form class="site-search-form">
  <input type="text" id="st-search-input" class="st-search-input st-default-search-input" />
</form>

<script type="text/javascript">
  (function(w,d,t,u,n,s,e){w['SwiftypeObject']=n;w[n]=w[n]||function(){
    (w[n].q=w[n].q||[]).push(arguments);};s=d.createElement(t);
    e=d.getElementsByTagName(t)[0];s.async=1;s.src=u;e.parentNode.insertBefore(s,e);
  })(window,document,'script','//s.swiftypecdn.com/install/v2/st.js','_st');

  _st('install', 'fLM9qfxyerC6njvM7usy','2.0.0');
</script>



    </div>
  
</nav>

 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  
  

  
  
  

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
            
            
              
                Java Lambda简明教程
              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">
            <span class="post-meta-item-icon">
              <i class="fa fa-calendar-o"></i>
            </span>
            <span class="post-meta-item-text">发表于</span>
            <time itemprop="dateCreated" datetime="2015-06-03T00:00:00+08:00" content="2015-06-03">
              2015-06-03
            </time>
          </span>

          
            <span class="post-category" >
              &nbsp; | &nbsp;
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
              
                <span itemprop="about" itemscope itemtype="https://schema.org/Thing">
                  <a href="/categories/java/" itemprop="url" rel="index">
                    <span itemprop="name">java</span>
                  </a>
                </span>

                
                
                  ， 
                

              
                <span itemprop="about" itemscope itemtype="https://schema.org/Thing">
                  <a href="/categories/java/lambda/" itemprop="url" rel="index">
                    <span itemprop="name">lambda</span>
                  </a>
                </span>

                
                

              
            </span>
          

          
            
              <span class="post-comments-count">
                &nbsp; | &nbsp;
                <a href="/blog/2015/06/java-lambda-expression.html#comments" itemprop="discussionUrl">
                  <span class="post-comments-count ds-thread-count" data-thread-key="/blog/2015/06/java-lambda-expression.html" itemprop="commentsCount"></span>
                </a>
              </span>
            
          

          

          
          
	
	<span id="busuanzi_container_page_pv" class="post-meta-item-text">
		&nbsp; | &nbsp;  
	    <span id="busuanzi_value_page_pv"><i class="fa fa-spinner fa-spin"></i></span> Hits
	</span>
        </div>
      </header>
    
	


    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>许多热门的编程语言如今都有一个叫做lambda或者闭包的语言特性，包括比较经典的函数式编程语言Lisp,Scheme,也有稍微年轻的语言比如JavaScript,Python,Ruby,Groovy,Scale,C#,甚至C++也有Lambda表达式。一些语言是运行在java虚拟机上，作为虚拟机最具代表的语言java当然也不想落后。<br><a id="more"></a></p>
<h1 id="究竟什么是Lambda表达式"><a href="#究竟什么是Lambda表达式" class="headerlink" title="究竟什么是Lambda表达式?"></a>究竟什么是Lambda表达式?</h1><p>Lambda表达式的概念来自于Lambda演算，下面是一个java lambda的简单例子，</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">(<span class="keyword">int</span> x) -&gt; &#123; <span class="keyword">return</span> x+<span class="number">1</span>; &#125;</span><br></pre></td></tr></table></figure>
<p>简单来看lambda像一个没有名字的方法，它具有一个方法应该有的部分：参数列表<code>int x</code>，方法body　<code>return x+1</code>,和方法相比lambda好像缺少了一个返回值类型、异常抛出和名字。返回值类型和异常是通过编译器在方法体中推导出来，在上面这个例子中返回值类型是int,没有抛出异常。真正缺少的就是一个名字，从这个角度来看，lambda表达式是一种匿名方法。</p>
<h1 id="Lambda表达式和匿名内部类"><a href="#Lambda表达式和匿名内部类" class="headerlink" title="Lambda表达式和匿名内部类"></a>Lambda表达式和匿名内部类</h1><p>从上面的分析可以看出lambda和java内部类的特性有点相似，匿名内部类不只是一个方法，而是一个包含一个或多个方法的类，他们的作用都是一样的，都是作为方法的参数传递，我从JDK源码中提取出来<code>listFiles(FileFilter)</code> 方法：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> File[] listFiles(FileFilter filter) &#123;</span><br><span class="line">	String ss[] = list();</span><br><span class="line">	<span class="keyword">if</span> (ss == <span class="keyword">null</span>) <span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">	</span><br><span class="line">	ArrayList&lt;File&gt; files = <span class="keyword">new</span> ArrayList&lt;&gt;();</span><br><span class="line">	<span class="keyword">for</span> (String s : ss) &#123;</span><br><span class="line">		File f = <span class="keyword">new</span> File(s, <span class="keyword">this</span>);</span><br><span class="line">		<span class="keyword">if</span> ((filter == <span class="keyword">null</span>) || filter.accept(f))</span><br><span class="line">		files.add(f);</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">return</span> files.toArray(<span class="keyword">new</span> File[files.size()]);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p><code>listFilter</code>方法接收一个功能接口作为参数，在这里是FileFilter接口：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">interface</span> <span class="title">FileFilter</span> </span>&#123;</span><br><span class="line">	<span class="function"><span class="keyword">boolean</span> <span class="title">accept</span><span class="params">(File pathname)</span></span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p><code>fileFilter</code>接收一个<code>File</code>对象返回一个<code>boolean</code>值，<code>listFiles</code>方法把<code>Filter</code>应用到所有的<code>File</code>对象接收 那些<code>accept</code>返回<code>true</code>的文件。对于<code>listFiles</code>方法来讲我们必须传递一个函数式接口给他，这是<code>FileFileter</code>的一个实现，一般我们通过匿名类来完成：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">File myDir = <span class="keyword">new</span> File(<span class="string">"／home/user/files"</span>);</span><br><span class="line"><span class="keyword">if</span> (myDir.isDirectory()) &#123;</span><br><span class="line">	File[] files = myDir.listFiles(</span><br><span class="line">	<span class="keyword">new</span> FileFilter() &#123;</span><br><span class="line">	 <span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">accept</span><span class="params">(File f)</span> </span>&#123; <span class="keyword">return</span> f.isFile(); &#125;</span><br><span class="line">	 &#125;</span><br><span class="line">	);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>　我们现在可以用lambda来实现：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">File myDir = <span class="keyword">new</span> File(<span class="string">"／home/user/files"</span>);</span><br><span class="line"><span class="keyword">if</span> (myDir.isDirectory()) &#123;</span><br><span class="line">	File[] files = myDir.listFiles(</span><br><span class="line">	(File f) -&gt; &#123; <span class="keyword">return</span> f.isFile(); &#125;</span><br><span class="line">	);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>这两种情况我们都是传递了一个函数式接口给方法就像传递对象一样，我们使用代码就像使用数据一样，使用匿名类我们实际上传递了一个对象给方法，使用lambda不再需要创建对象，我们只需要把lambda代码传递给方法。</p>
<p>除了传递lambda之外我们还可以传递一个方法引用，比如：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">File[] files = myDir.listFiles( File::isFile );</span><br></pre></td></tr></table></figure>
<h1 id="Lambda表达式的表示"><a href="#Lambda表达式的表示" class="headerlink" title="Lambda表达式的表示"></a>Lambda表达式的表示</h1><p>在之前的例子，我们使用lambda表达式定义了一个函数，我们可以把它作为参数传递给一个方法，方法把它当成一个对象来使用，lambda表达式有函数和对象的一些属性，看你从什么角度来看：</p>
<ul>
<li>从概念来讲，lambda表达式是一个匿名函数，它有签名和方法体但是没有名字</li>
<li>当lambda表达式作为参数传递给方法时，接收方法把它当对象使用，在<code>listFiles</code>方法内部，lambda表达式是一个对象的引用，在这里lambda表达式是一种常规的对象，比如有地址和类型。</li>
</ul>
<p>从实际的角度来分析，lambda对象是由编译期和运行时系统来创建的，这就允许编译期进行优化而使用者不需要关心具体细节，编译器从lambda表达式的上下文环境来获取lambda对象的语义类型，但是编译期并不创建那个对象而是直到运行时由虚拟机动态创建，这里说的动态创建是指调用<code>invokedynamic</code>字节码指令来创建。使用动态创建可以推迟对象的创建到对象第一次被使用时，如果你只是定义了lambda表达式而从未使用，它的类型和对象都不会创建。</p>
<h1 id="函数式接口"><a href="#函数式接口" class="headerlink" title="函数式接口"></a>函数式接口</h1><p>整个魔幻之处就在于类型的推导，这个类型称为目标类型，运行时系统动态创建的类型是目标类型的子类型。之前的那个例子我们看到目标类型是<code>FileFilter</code>,在例子中我们定义了一个lambda表达式把它传递给listFiles方法，然后listFiles方法把它作为<code>FileFilter</code>子类的一个对象来使用。这里看起来好像有点神奇，我们并没有声明lambda表达式实现了<code>FileFilter</code>接口，<code>listFiles</code>方法也没有表明它很愉快的接收了lambda表达式，它只是需要一个<code>FileFilter</code>的子类的对象，这是如何工作的？</p>
<p>这里面的魔术在于编译期执行了类型推导，编译器根据lambda表达式的上下文来决定需要什么类型的对象，然后编译器观察lambda表达式是否兼容需要的类型。如果Java是一种函数式编程语言的话lambda表达式最自然的类型就是某种函数式类型，用来描述函数的一种特殊类型。函数式类型仅仅描述了函数的签名比如<code>(int,int)-&gt;boolean</code>.但是Java不是函数式编程语言因此没有函数式类型，语言的设计者可以选择添加一种新的类型，由于他们不想给Java的类型系统引入太多的改变，因此他们尝试寻找一种办法来集成lambda表达式到语言中而不需要添加函数式类型。</p>
<p>结果他们使用函数式接口来代替，函数式接口是只有一个方法的接口，这样的接口在JDK里有很多，比如经典的Runnable接口，它只有一个方法<code>void run()</code>,还有很多其他的，比如<code>Readable,Callable,Iterable,closeable,Flushnable,Formattable,Comparable,Comparator</code>,或者我们前面提到的<code>FileFilter</code>接口。函数是接口和lambda表达式奕扬都只有一个方法，语言的设计者决定让编译器把lambda表达式转换成匹配的函数式接口。这种转换通常是自动的。比如我们前面提到的<code>(File f) -&gt; { return f.isFile(); }</code>,编译器知道listFiles方法的签名，因此我们需要的类型就是<code>FileFilter</code>,<code>FileFilter</code>是这样的：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">interface</span> <span class="title">FileFilter</span> </span>&#123; <span class="function"><span class="keyword">boolean</span> <span class="title">accept</span><span class="params">(File pathname)</span></span>; &#125;</span><br></pre></td></tr></table></figure>
<p>FileFilter仅仅需要一个方法因此它是函数式接口类型，我们定义的lambda表达式有一个相匹配的签名，接收一个<code>File</code>对象，返回一个<code>boolean</code>值，不抛出检查的异常，因此编译器把lambda表达式转换成函数式接口<code>FileFilter</code>类型。</p>
<p>假如我们有下面两个函数式接口：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">interface</span> <span class="title">FileFilter</span> </span>&#123; <span class="function"><span class="keyword">boolean</span> <span class="title">accept</span><span class="params">(File pathname)</span></span>; &#125;</span><br><span class="line">　</span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">interface</span> <span class="title">Predicate</span>&lt;<span class="title">T</span>&gt; </span>&#123; <span class="function"><span class="keyword">boolean</span> <span class="title">test</span><span class="params">(T t)</span></span>; &#125;</span><br></pre></td></tr></table></figure>
<p>我们的lambda表达式兼容两种函数式接口类型：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">FileFilter filter = (File f) -&gt; &#123; <span class="keyword">return</span> f.isFile(); &#125;;</span><br><span class="line"></span><br><span class="line">Predicate&lt;File&gt; predicate = (File f) -&gt; &#123; <span class="keyword">return</span> f.isFile(); &#125;;</span><br><span class="line"></span><br><span class="line">filter = predicate;<span class="comment">//错误，不兼容的类型</span></span><br></pre></td></tr></table></figure>
<p>当我们试图给两个变量相互赋值时编译器会报错，虽然两个变量都是同一个lambda表达式，原因很简单两个变量是不同的类型。也有可能出现编译器无法判断匹配的函数式接口类型，比如这个例子：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">Object ref　= (File f) -&gt; &#123; <span class="keyword">return</span> f.isFile(); &#125;;</span><br></pre></td></tr></table></figure>
<p>这个赋值语句的上下文没有提供足够的信息来转换，因此编译器会报错，解决这个问题最简单的方法就是添加一个类型转换：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">　	Object ref　= (FileFilter) (File f) -&gt; &#123; <span class="keyword">return</span> f.isFile(); &#125;;</span><br></pre></td></tr></table></figure>
<h1 id="Lambda表达式和匿名内部类的区别"><a href="#Lambda表达式和匿名内部类的区别" class="headerlink" title="Lambda表达式和匿名内部类的区别"></a>Lambda表达式和匿名内部类的区别</h1><p>Lambda表达式出现在我们通常需要匿名内部类的地方，在很多场合他们是可以互换的。但是他们还是有几个区别：</p>
<h3 id="语法"><a href="#语法" class="headerlink" title="语法"></a>语法</h3><p>匿名类一般这样编写：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">File[] fs = myDir.<span class="function">lis <span class="title">tFiles</span><span class="params">(</span><br><span class="line">	new FileFilter()</span> </span>&#123;</span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">accept</span><span class="params">(File f)</span> </span>&#123; <span class="keyword">return</span> f.isFile(); &#125;</span><br><span class="line">	&#125;</span><br><span class="line">);</span><br></pre></td></tr></table></figure>
<p>而Lambda表达式有多种形式：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">File[] files = myDir.listFiles( (File f) -&gt; &#123;<span class="keyword">return</span> f.isFile();&#125; );</span><br><span class="line">File[] files = myDir.listFiles( f -&gt; f.isFile() );</span><br><span class="line">F ile[] fil e s = myDir.listFiles( File::isFile );</span><br></pre></td></tr></table></figure>
<h3 id="运行时成本"><a href="#运行时成本" class="headerlink" title="运行时成本"></a>运行时成本</h3><p>匿名类相对Lambda表达式来讲多了一些成本，使用匿名类或造成新类型的创建、新类型对象的创建。运行时匿名内需要：</p>
<ul>
<li>类加载</li>
<li>内存分配、对象初始化</li>
<li>调用非静态方法</li>
</ul>
<p>Lambda表达式需要函数式接口的转换和最终的调用，类型推导发生在编译期，不需要运行时消耗，之前提到过，lambda对象的创建是通过字节码指令<code>invokedynamic</code>来完成的，减少了类型和实例的创建消耗。</p>
<h3 id="变量绑定"><a href="#变量绑定" class="headerlink" title="变量绑定"></a>变量绑定</h3><p>匿名类可以访问外部域的<code>final</code>变量，如下所示：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">method</span><span class="params">()</span> </span>&#123;</span><br><span class="line">	<span class="keyword">final</span> <span class="keyword">int</span> cnt = <span class="number">16</span>;</span><br><span class="line"></span><br><span class="line">	Runnable r = <span class="keyword">new</span> Runnable() &#123;</span><br><span class="line">		<span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">run</span><span class="params">()</span> </span>&#123;</span><br><span class="line">		System.out.println(<span class="string">"count: "</span> + cnt);</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;;</span><br><span class="line">	Thread t = <span class="keyword">new</span> Thread(r);</span><br><span class="line">	t.start();</span><br><span class="line"></span><br><span class="line">	cnt++;<span class="comment">// error: cnt is final</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>对于lambda表达式，cnt变量不需要显式声明为final的，一旦变量在lambda中使用编译期会自动把它当成是<code>final</code>的变量，换句话说在lambda中使用的外部域变量是隐式final的，</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">method</span><span class="params">()</span> </span>&#123;</span><br><span class="line">	<span class="keyword">int</span> cnt = <span class="number">16</span>;</span><br><span class="line"></span><br><span class="line">	Runnable r = () -&gt; &#123; System.out.println(<span class="string">"count: "</span> + cnt);</span><br><span class="line">	&#125;;</span><br><span class="line">	Thread t = <span class="keyword">new</span> Thread(r);</span><br><span class="line">	t.start();</span><br><span class="line"></span><br><span class="line">	cnt++;<span class="comment">// error: cnt is implicitly final</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>从java8开始匿名内部类也不需要再显式声明final类，编译器会自动把它当成是final。</p>
<h2 id="作用域"><a href="#作用域" class="headerlink" title="作用域"></a>作用域</h2><p>匿名内部类是一个类，也就是说它自己引入了一个作用域，你可以在里面定义变量，而lambda表达式没有自己的作用域。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">method</span><span class="params">()</span> </span>&#123;</span><br><span class="line">	<span class="keyword">int</span> cnt = <span class="number">16</span>;</span><br><span class="line">	Runnable r = <span class="keyword">new</span> Runnable() &#123;</span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">run</span><span class="params">()</span> </span>&#123; <span class="keyword">int</span> cnt = <span class="number">0</span>; <span class="comment">// fine</span></span><br><span class="line">		System.out.println(<span class="string">"cnt is: "</span> + cnt); &#125;</span><br><span class="line">		&#125;;</span><br><span class="line">　</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>lambda表达式：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">method</span><span class="params">()</span> </span>&#123;</span><br><span class="line">	<span class="keyword">int</span> cnt = <span class="number">16</span>;</span><br><span class="line">	Runnable r = () -&gt; &#123; <span class="keyword">int</span> cnt = <span class="number">0</span>; <span class="comment">// error: cnt has already been defined</span></span><br><span class="line">		System.out.println(<span class="string">"cnt is: "</span> + cnt);</span><br><span class="line">	&#125;;</span><br><span class="line">　</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>不同的作用域规则对于<code>this</code>和<code>super</code>关键字有不同的效果，在匿名类中<code>this</code>表示匿名类对象本身的引用，<code>super</code>表示匿名类的父类。在lambda表达式<code>this</code>和<code>super</code>关键字意思和外部域中<code>this</code>和<code>super</code>的意思一样，<code>this</code>一般是包含它的那个对象，<code>super</code>表示包含它的类的父类。</p>

      
    </div>

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/java/" rel="tag">#java</a>
          
        </div>
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/blog/2015/05/android-links.html" rel="next" title="安卓开发者必备的42个链接">
                <i class="fa fa-chevron-left"></i> 安卓开发者必备的42个链接
              </a>
            
          </div>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/blog/2015/07/hibernate-cache-guide.html" rel="prev" title="Hibernate缓存配置笔记">
                Hibernate缓存配置笔记 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </article>



    <div class="post-spread">
      
        <div class="ds-share flat" data-thread-key="/blog/2015/06/java-lambda-expression.html"
     data-title="Java Lambda简明教程"
     data-content=""
     data-url="http://www.ezlippi.com//blog/2015/06/java-lambda-expression.html">
  <div class="ds-share-inline">
    <ul  class="ds-share-icons-16">

      <li data-toggle="ds-share-icons-more"><a class="ds-more" href="javascript:void(0);">分享到：</a></li>
      <li><a class="ds-weibo" href="javascript:void(0);" data-service="weibo">微博</a></li>
      <li><a class="ds-qzone" href="javascript:void(0);" data-service="qzone">QQ空间</a></li>
      <li><a class="ds-qqt" href="javascript:void(0);" data-service="qqt">腾讯微博</a></li>
      <li><a class="ds-wechat" href="javascript:void(0);" data-service="wechat">微信</a></li>

    </ul>
    <div class="ds-share-icons-more">
    </div>
  </div>
</div>
      
    </div>
  </div>


          </div>
          

  <p>热评文章</p>
  <div class="ds-top-threads" data-range="weekly" data-num-items="4"></div>


          
  <div class="comments" id="comments">
    
      <div class="ds-thread" data-thread-key="/blog/2015/06/java-lambda-expression.html"
           data-title="Java Lambda简明教程" data-url="http://www.ezlippi.com//blog/2015/06/java-lambda-expression.html">
      </div>
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel ">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image"
               src="/images/avatar.jpg"
               alt="EZLippi" />
          <p class="site-author-name" itemprop="name">EZLippi</p>
          <p class="site-description motion-element" itemprop="description">Easy Lippi</p>
        </div>
        <nav class="site-state motion-element">
          <div class="site-state-item site-state-posts">
            <a href="/archives">
              <span class="site-state-item-count">63</span>
              <span class="site-state-item-name">日志</span>
            </a>
          </div>
          
          
            <div class="site-state-item site-state-categories">
              <a href="/categories">
                <span class="site-state-item-count">22</span>
                <span class="site-state-item-name">分类</span>
              </a>
            </div>
          

          
            <div class="site-state-item site-state-tags">
              <a href="/tags">
                <span class="site-state-item-count">69</span>
                <span class="site-state-item-name">标签</span>
              </a>
            </div>
          

        </nav>

        
          <div class="feed-link motion-element">
            <a href="/atom.xml" rel="alternate">
              <i class="fa fa-rss"></i>
              RSS
            </a>
          </div>
        

        <div class="links-of-author motion-element">
          
            
              <span class="links-of-author-item">
                <a href="https://github.com/EZLippi" target="_blank">
                  
                    <i class="fa fa-github"></i> GitHub
                  
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="http://weibo.com/ouyanglip" target="_blank">
                  
                    <i class="fa fa-weibo"></i> weibo
                  
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="http://www.zhihu.com/people/lippi-ouyang" target="_blank">
                  
                    <i class="fa fa-weibo"></i> zhihu
                  
                </a>
              </span>
            
          
        </div>

        
        

        <div class="links-of-author motion-element">
          
            <p class="site-author-name">友情链接</p>
            
              <span class="links-of-author-item">
                <a href="http://szhshp.org" target="_blank">szhshp的博客</a>
              </span>
            
              <span class="links-of-author-item">
                <a href="https://www.zhihu.com/people/lippi-ouyang" target="_blank">友链出租</a>
              </span>
            
          
        </div>

      </section>

      
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc-indicator-top post-toc-indicator">
            <i class="fa fa-angle-double-up"></i>
          </div>
          <div class="post-toc">
            
              
            
            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#究竟什么是Lambda表达式"><span class="nav-number">1.</span> <span class="nav-text">究竟什么是Lambda表达式?</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#Lambda表达式和匿名内部类"><span class="nav-number">2.</span> <span class="nav-text">Lambda表达式和匿名内部类</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#Lambda表达式的表示"><span class="nav-number">3.</span> <span class="nav-text">Lambda表达式的表示</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#函数式接口"><span class="nav-number">4.</span> <span class="nav-text">函数式接口</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#Lambda表达式和匿名内部类的区别"><span class="nav-number">5.</span> <span class="nav-text">Lambda表达式和匿名内部类的区别</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#语法"><span class="nav-number">5.0.1.</span> <span class="nav-text">语法</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#运行时成本"><span class="nav-number">5.0.2.</span> <span class="nav-text">运行时成本</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#变量绑定"><span class="nav-number">5.0.3.</span> <span class="nav-text">变量绑定</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#作用域"><span class="nav-number">5.1.</span> <span class="nav-text">作用域</span></a></li></ol></li></ol></div>
            
          </div>
          <div class="post-toc-indicator-bottom post-toc-indicator">
            <i class="fa fa-angle-double-down"></i>
          </div>
        </section>
      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  
  &copy;  2014 - 
  <span itemprop="copyrightYear">2016</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">EZLippi</span>
</div>

<div class="powered-by">
  由 <a class="theme-link" href="http://hexo.io">Hexo</a> 强力驱动
</div>

<div class="theme-info">
   托管在 -
  <a class="theme-link" href="https://github.com/EZLippi/EZLippi.github.io">
    Github
  </a>

</div>
<div class="theme-info">
<span id="busuanzi_container_site_pv">
    &nbsp; | &nbsp;本站总访问量<span id="busuanzi_value_site_pv"></span>次
</span>
</div>
<script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js">
</script>



      </div>
    </footer>

    <div class="back-to-top"></div>
  </div>

  


  



  <script type="text/javascript" src="/vendors/jquery/index.js?v=2.1.3"></script>

  <script type="text/javascript" src="/vendors/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  <script type="text/javascript" src="/vendors/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  <script type="text/javascript" src="/vendors/velocity/velocity.min.js"></script>

  <script type="text/javascript" src="/vendors/velocity/velocity.ui.min.js"></script>

  <script type="text/javascript" src="/vendors/fancybox/source/jquery.fancybox.pack.js"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=0.5.0"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=0.5.0"></script>



  
  

  
  
<script type="text/javascript" src="/js/src/scrollspy.js?v=0.5.0"></script>

<script type="text/javascript" id="sidebar.toc.highlight">
  $(document).ready(function () {
    var tocSelector = '.post-toc';
    var $tocSelector = $(tocSelector);
    var activeCurrentSelector = '.active-current';

    $tocSelector
      .on('activate.bs.scrollspy', function () {
        var $currentActiveElement = $(tocSelector + ' .active').last();

        removeCurrentActiveClass();
        $currentActiveElement.addClass('active-current');

        $tocSelector[0].scrollTop = $currentActiveElement.position().top;
      })
      .on('clear.bs.scrollspy', function () {
        removeCurrentActiveClass();
      });

    function removeCurrentActiveClass () {
      $(tocSelector + ' ' + activeCurrentSelector)
        .removeClass(activeCurrentSelector.substring(1));
    }

    function processTOC () {
      getTOCMaxHeight();
      toggleTOCOverflowIndicators();
    }

    function getTOCMaxHeight () {
      var height = $('.sidebar').height() -
                   $tocSelector.position().top -
                   $('.post-toc-indicator-bottom').height();

      $tocSelector.css('height', height);

      return height;
    }

    function toggleTOCOverflowIndicators () {
      tocOverflowIndicator(
        '.post-toc-indicator-top',
        $tocSelector.scrollTop() > 0 ? 'show' : 'hide'
      );

      tocOverflowIndicator(
        '.post-toc-indicator-bottom',
        $tocSelector.scrollTop() >= $tocSelector.find('ol').height() - $tocSelector.height() ? 'hide' : 'show'
      )
    }

    $(document).on('sidebar.motion.complete', function () {
      processTOC();
    });

    $('body').scrollspy({ target: tocSelector });
    $(window).on('resize', function () {
      if ( $('.sidebar').hasClass('sidebar-active') ) {
        processTOC();
      }
    });

    onScroll($tocSelector);

    function onScroll (element) {
      element.on('mousewheel DOMMouseScroll', function (event) {
          var oe = event.originalEvent;
          var delta = oe.wheelDelta || -oe.detail;

          this.scrollTop += ( delta < 0 ? 1 : -1 ) * 30;
          event.preventDefault();

          toggleTOCOverflowIndicators();
      });
    }

    function tocOverflowIndicator (indicator, action) {
      var $indicator = $(indicator);
      var opacity = action === 'show' ? 1 : 0;
      $indicator.velocity ?
        $indicator.velocity('stop').velocity({
          opacity: opacity
        }, { duration: 100 }) :
        $indicator.stop().animate({
          opacity: opacity
        }, 100);
    }

  });
</script>

<script type="text/javascript" id="sidebar.nav">
  $(document).ready(function () {
    var html = $('html');
    var TAB_ANIMATE_DURATION = 200;
    var hasVelocity = $.isFunction(html.velocity);

    $('.sidebar-nav li').on('click', function () {
      var item = $(this);
      var activeTabClassName = 'sidebar-nav-active';
      var activePanelClassName = 'sidebar-panel-active';
      if (item.hasClass(activeTabClassName)) {
        return;
      }

      var currentTarget = $('.' + activePanelClassName);
      var target = $('.' + item.data('target'));

      hasVelocity ?
        currentTarget.velocity('transition.slideUpOut', TAB_ANIMATE_DURATION, function () {
          target
            .velocity('stop')
            .velocity('transition.slideDownIn', TAB_ANIMATE_DURATION)
            .addClass(activePanelClassName);
        }) :
        currentTarget.animate({ opacity: 0 }, TAB_ANIMATE_DURATION, function () {
          currentTarget.hide();
          target
            .stop()
            .css({'opacity': 0, 'display': 'block'})
            .animate({ opacity: 1 }, TAB_ANIMATE_DURATION, function () {
              currentTarget.removeClass(activePanelClassName);
              target.addClass(activePanelClassName);
            });
        });

      item.siblings().removeClass(activeTabClassName);
      item.addClass(activeTabClassName);
    });

    $('.post-toc a').on('click', function (e) {
      e.preventDefault();
      var targetSelector = NexT.utils.escapeSelector(this.getAttribute('href'));
      var offset = $(targetSelector).offset().top;
      hasVelocity ?
        html.velocity('stop').velocity('scroll', {
          offset: offset  + 'px',
          mobileHA: false
        }) :
        $('html, body').stop().animate({
          scrollTop: offset
        }, 500);
    });

    // Expand sidebar on post detail page by default, when post has a toc.
    NexT.motion.middleWares.sidebar = function () {
      var $tocContent = $('.post-toc-content');

      if (CONFIG.sidebar.display === 'post' || CONFIG.sidebar.display === 'always') {
        if ($tocContent.length > 0 && $tocContent.html().trim().length > 0) {
          NexT.utils.displaySidebar();
        }
      }
    };
  });
</script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=0.5.0"></script>



  

  
    
  

  <script type="text/javascript">
    var duoshuoQuery = {short_name:"ezlippi"};
    (function() {
      var ds = document.createElement('script');
      ds.type = 'text/javascript';ds.async = true;
      ds.id = 'duoshuo-script';
      ds.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') + '//static.duoshuo.com/embed.js';
      ds.charset = 'UTF-8';
      (document.getElementsByTagName('head')[0]
      || document.getElementsByTagName('body')[0]).appendChild(ds);
    })();
  </script>

  
    
  





  
  

  
  


</body>
</html>
